package com.example.springboot.Interceptor;


import com.example.springboot.common.constants.Constants;
import com.example.springboot.common.system.UserHolder;
import com.example.springboot.common.utils.StringUtils.StringUtils;
import com.example.springboot.common.utils.ThrowUtil.ThrowUtil;
import com.example.springboot.entity.LoginUser;
import com.example.springboot.service.TokenService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.example.springboot.common.constants.Constants.UNAUTHORIZED;

//校验令牌，刷新
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null) {
            tokenService.verifyToken(loginUser);
            UserHolder.saveLoginUser(loginUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserHolder.removeLoginManager();
    }

}
